package com.jian.mall.interceptor;

import com.jian.mall.common.constant.UserConstant;
import com.jian.mall.common.redis.User;
import com.jian.mall.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<User> userInfoThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(UserConstant.USER_LOGIN_STATUS);
        if (userInfo != null) {
            // 登录了
            userInfoThreadLocal.set(userInfo);
            return true;
        }
        // 没有登录
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        userInfoThreadLocal.remove();
    }
}
